package com.hb.trade.server.center.au.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.center.au.dto.AgencyUserBidDTO;
import com.hb.core.pojo.center.au.dto.RoleDTO;
import com.hb.core.pojo.center.au.dto.UserDTO;
import com.hb.core.pojo.center.au.entity.User;
import com.hb.core.pojo.center.au.entity.UserExt;
import com.hb.core.pojo.center.au.mapper.UserMapper;
import com.hb.core.pojo.parent.PageResult;
import com.hb.trade.server.center.au.service.UserExtService;
import com.hb.trade.server.center.au.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 系统用户表，表中用户包括两种类型，系统管理用户和招标业务用户 服务实现类
 *
 * @author zhaojk
 * @since 2021-11-29
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final static String EXISTS_ERROR_FORMATTER = "{}: [{}], 该数据已经存在";

    protected final UserExtService userExtService;

    public UserServiceImpl(UserExtService userExtService) {
        this.userExtService = userExtService;
    }

    @Override
    public boolean existsInBlackList(Serializable usernameOrUserId) {
        return baseMapper.existsInBlackList(usernameOrUserId) != null;
    }

    /**
     * 查询指定企业下的所有用户
     *
     * @param orgId
     * @return
     */
    @Override
    public List<User> listByOrgId(Long orgId) {
        QueryWrapper<User> wrapper = User.wrapper();
        wrapper.eq("org_id", orgId);
        return list(wrapper);
    }

    /**
     * 仅通过用户名和手机号判断用户是否存在
     *
     * @param user
     * @return
     */
    @Override
    public User exists(User user) {
        // 判断登录用户名
        String username = user.getUsername();
        QueryWrapper<User> wrapper = User.wrapper();
        wrapper.eq("username", username).last("limit 1");
        User rawUser = getOne(wrapper);
        if (rawUser != null) {
            log.info(EXISTS_ERROR_FORMATTER, "登录用户名", username);
            return rawUser;
        }

        // 判断用户手机号码
//        String phone = user.getPhone();
//        wrapper.clear();
//        wrapper.eq("phone", phone).last("limit 1");
//        rawUser = getOne(wrapper);
//        if (rawUser != null) {
//            log.info(EXISTS_ERROR_FORMATTER, "手机号码", phone);
//            return rawUser;
//        }

        return null;
    }

    /**
     * 查询指定角色下的用户成员列表
     *
     * @param roleDTO#id       角色ID
     * @param roleDTO#pageFlag 返回形式(1: 分页对象, 2: 列表对象)
     * @return
     */
    @Override
    public Object usersByRoleId(RoleDTO roleDTO) {
        Integer pageFlag = roleDTO.getPageFlag();
        if (pageFlag == null) {
            pageFlag = 1;
        }

        Long roleId = roleDTO.getId();

        // 返回分页对象
        if (Integer.valueOf(1).equals(pageFlag)) {
            Page<User> pages = roleDTO.pages();
            return pageUsersByRoleId(pages, roleId, roleDTO.getOrgId());
        }
        // 返回数组
        if (Integer.valueOf(2).equals(pageFlag)) {
            return listUsersByRoleId(roleId, roleDTO.getOrgId());
        }
        return null;
    }

    @Override
    public List<User> listUsersByRoleId(Long roleId, Long orgId) {
        return baseMapper.listUsersByRoleId(roleId, orgId);
    }

    @Override
    public PageResult<User> pageUsersByRoleId(Page<User> pages, Long roleId, Long orgId) {
        Page<User> userPage = baseMapper.pageUsersByRoleId(pages, roleId, orgId);
        return PageResult.get(userPage);
    }

    /**
     * Description: 核对中招扫码信息是否与当前登录人一致
     *
     * @param zaphoneNum 中招扫码信息·手机号
     * @param offerId    投标人id
     * @author: fengbin
     * @date: 2022/2/23 13:51
     * @return: java.lang.Boolean
     */
    @Override
    public Boolean zappUserConfirmInfo(String zaphoneNum, Long offerId) {
        //根据投标人id获取投标人手机号
        User user = baseMapper.selectById(offerId.toString());
        if (ObjectUtils.isEmpty(user)) {
            return false;
        }
        boolean equals = zaphoneNum.equals(user.getPhone());
        return equals;
    }

    @Override
    public boolean addSystemUser(UserDTO userDTO) {
        // 新增用户主表信息
        boolean save = save(userDTO);
        if (save) {
            Long id = userDTO.getId();
            UserExt userExt = userDTO.getUserExt();
            // 保存用户扩展信息
            if (userExt != null) {
                userExt.buildBaseData(1);
                userExt.setUserId(id);
                return userExtService.save(userExt);
            }
            return true;
        }
        return false;
    }

    @Override
    public PageResult<UserDTO> pageAuditUser(AgencyUserBidDTO agencyUserDTO) {
        UserDTO userDTO = new UserDTO();
        //复制分页属性
        BeanUtil.copyProperties(agencyUserDTO, userDTO);
        Page pages = userDTO.pages();
        baseMapper.pageAuditUser(pages, agencyUserDTO.getUsername(), agencyUserDTO.getOrgName(), agencyUserDTO.getUserStatus(), agencyUserDTO.getType());
        return PageResult.get(pages);
    }

    @Override
    public boolean examine(Long id, Integer userStatus, String reason) {
        User user = getById(id);
        if (user == null) {
            return false;
        }
        user.setUserStatus(userStatus);
        //设置审核时间
        user.setAuditTime(LocalDateTime.now());

        if (StrUtil.isNotEmpty(reason)) {
            user.setReason(reason);
        }
        return updateById(user);
    }

    @Override
    public User getUserByRoleAndIdNum(Long roleId, String idNum) {
        User user = baseMapper.getUserByRoleAndIdNum(roleId, idNum);
        return user;
    }

    @Override
    public List<User> getUserByPhoneAndRoleSign(List<Long> roleIds, String phone, Long orgId) {
        List<User> users = baseMapper.getUserByPhoneAndRoleSign(roleIds, phone, orgId);
        return users;
    }

    @Override
    public User getUserByOrgIdAndRoleId(Long roleId, Long orgId) {
        User user = baseMapper.getUserByOrgIdAndRoleId(roleId, orgId);
        return user;
    }

    /**
     * @param orgId:企业id
     * @param userId:用户id(userId 不为空则除了当前userId 为空则查询企业的)
     * @param userStatus:用户状态
     * @Description:查询当前企业审核状态的数量
     * @Author: zhongdl
     * @Date:2022/4/13 14:11
     * @return: {@link int }
     **/
    @Override
    public int approvedCount(Long orgId, Long userId, Integer userStatus) {
        QueryWrapper<User> wrapper = User.wrapper();
        wrapper.eq("org_id", orgId)
                .ne(userId != null, "id", userId)
                .eq("user_status", userStatus)
                .exists("select 1 from au_user_role aa inner join  au_role bb on aa.role_id = bb.id where bb.role_sign in (1,3) and aa.user_id = " + userId);
        long count = count(wrapper);
        return Integer.parseInt(String.valueOf(count));
    }

    /**
     * 分页获取指定查询条件的用户列表
     *
     * @param pages
     * @param userDto
     */
    @Override
    public Page<User> pageUsers(Page<User> pages, UserDTO userDto) {
        return baseMapper.pageUsers(pages, userDto);
    }


    /**
     * 根据企业id集合查询用户
     *
     * @param orgIdList
     * @return org.fzzn.core.model.msg.Message
     * @author yuezheng
     * @date 2022/4/23 10:12 AM
     */
    @Override
    public List<User> findUserByOrgList(List<String> orgIdList) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "phone", "user_type", "org_id").lambda().in(User::getOrgId, orgIdList);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据id查询投标人
     *
     * @param userList
     * @return org.fzzn.core.model.msg.Message
     * @author yuezheng
     * @date 2022/4/23 10:12 AM
     */
    @Override
    public List<User> finBidUserByUserList(List<User> userList) {
        Set<Long> userId = userList.stream().map(User::getId).collect(Collectors.toSet());
        return baseMapper.finBidUserByUserList(userId);
    }

    /**
     * 查询企业下的管理员
     *
     * @author tian
     * @date 2022-5-19 13:57
     * @param userDTO
     * @return com.hb.core.pojo.center.au.entity.User
     */
    @Override
    public User findManagerByOrgId(UserDTO userDTO) {
        return baseMapper.findManagerByOrgId(userDTO);
    }

    @Override
    public User getUserByUnifiedTransactionCodeAndRoleIds(String unifiedTransactionCode, List<Long> roleIds){
        return baseMapper.getUserByUnifiedTransactionCodeAndRoleIds(roleIds, unifiedTransactionCode);
    }

    /**
     * 根据机构交易猫和roleSign查询用户
     * @param unifiedTransactionCode
     * @param roleSign
     * @return
     */
    @Override
    public User getUserByUnifiedTransactionCodeAndRoleSign(String unifiedTransactionCode, Integer roleSign){
        return baseMapper.getUserByUnifiedTransactionCodeAndRoleSign(unifiedTransactionCode, roleSign);
    }

}
